<template>
  <div class="reservoir-area-container">
    <!-- 页面头部 -->
    <el-page-header @back="goBack" class="page-header">
      <template #content>
        <span class="header-title">库区设置</span>
      </template>
    </el-page-header>

    <!-- 搜索区域 -->
    <div class="search-card">
      <el-form :inline="true" class="search-form">
        <el-form-item label="库区名称">
          <el-input
            v-model="sreach.reservoirAreaName"
            placeholder="请输入库区名称"
            clearable
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="funShow" :loading="loading">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-card">
      <div class="card-header">
        <div class="header-title">
          <el-icon><List /></el-icon>
          库区列表
        </div>
        <el-button type="primary" @click="OpenAdd" class="add-button">
          <el-icon><Plus /></el-icon>新增库区
        </el-button>
      </div>
      
      <el-table 
        v-loading="loading"
        :data="tableData" 
        border 
        stripe
        highlight-current-row
        style="width: 1370px"
        class="data-table"
      >
        <el-table-column prop="reservoirAreaCode" label="库区编号" min-width="120" />
        <el-table-column prop="reservoirAreaName" label="库区名称" min-width="150" />
        <el-table-column prop="area" label="面积" min-width="100">
          <template #default="scope">
            {{ scope.row.area }} m²
          </template>
        </el-table-column>
        <el-table-column prop="descs" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="scope">
            <el-button type="success" link @click="handleArea(scope.row)">
              <el-icon><Guide /></el-icon>库位
            </el-button>
            <el-button type="primary" link @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="page.pageIndex"
          v-model:page-size="page.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.totalCount"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      v-model="dialogFormVisible" 
      :title="form.id ? '编辑库区信息' : '新增库区信息'" 
      width="500px"
      destroy-on-close
      :close-on-click-modal="false"
      class="custom-dialog"
    >
      <el-form 
        :model="form" 
        label-width="100px"
        :rules="rules"
        ref="formRef"
        class="custom-form"
        :validate-on-rule-change="false"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon><Document /></el-icon>
            基本信息
          </div>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="库区编号" prop="reservoirAreaCode">
                <div class="code-input-group">
                  <el-input 
                    v-model="form.reservoirAreaCode" 
                    placeholder="请输入库区编号" 
                    :disabled="form.id !== 0 || autoGenerate"
                    class="code-input"
                    :maxlength="20"
                    show-word-limit
                  >
                    <template #prefix>
                      <el-icon><Location /></el-icon>
                    </template>
                  </el-input>
                  <el-switch
                    v-model="autoGenerate"
                    :disabled="form.id !== 0"
                    active-text="自动生成"
                    class="auto-switch"
                    @change="handleAutoGenerateChange"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="库区名称" prop="reservoirAreaName">
                <el-input 
                  v-model="form.reservoirAreaName" 
                  placeholder="请输入库区名称"
                  :maxlength="50"
                  show-word-limit
                >
                  <template #prefix>
                    <el-icon><Edit /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 规格信息 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon><Setting /></el-icon>
            规格信息
          </div>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="面积" prop="area">
                <el-input-number 
                  v-model="form.area" 
                  :min="0"
                  :precision="2"
                  :step="100"
                  style="width: 100%"
                  placeholder="请输入面积"
                  controls-position="right"
                >
                  <template #suffix>m²</template>
                </el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 其他信息 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon><InfoFilled /></el-icon>
            其他信息
          </div>
          <el-form-item label="备注">
            <el-input 
              type="textarea" 
              v-model="form.descs" 
              placeholder="请输入备注信息"
              :rows="3"
              :maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Edit, 
  Delete, 
  List, 
  Location,
  Document,
  Setting,
  InfoFilled
} from '@element-plus/icons-vue'
import http from '@/api/http'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
const router = useRouter()
const route = useRoute()
const formRef = ref()

// 加载状态
const loading = ref(false)
const saveLoading = ref(false)

// 查询条件
const sreach = reactive({
  reservoirAreaName: '',
})

// 分页条件
const page = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  totalPage: 0
})

// 表单校验规则
const rules = {
  reservoirAreaCode: [
    { required: true, message: '请输入库区编号', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  reservoirAreaName: [
    { required: true, message: '请输入库区名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请输入面积', trigger: 'blur' }
  ]
}

// 表单数据
const form = reactive({
  id: 0,
  warehouseCode: route.query.warehouseCode,
  reservoirAreaCode: '',
  reservoirAreaName: '',
  area: '',
  descs: ''
})

// 表格数据
const tableData = ref([])

// 添加自动生成开关状态
const autoGenerate = ref(false)

// 获取数据列表
const funShow = async () => {
  try {
    loading.value = true
    const res = await axios.get('http://localhost:9991/api/WarehouseManagement/GetReservoirAreaPageList', {
      params: {
        pageIndex: page.pageIndex,
        pageSize: page.pageSize,
        reservoirAreaName: sreach.reservoirAreaName,
        warehouseCode: route.query.warehouseCode
      }
    })
    tableData.value = res.data.data
    page.totalCount = res.data.totalCount
    page.totalPage = res.data.totalPages
  } catch (error: any) {
    ElMessage.error('获取数据失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  sreach.reservoirAreaName = ''
  page.pageIndex = 1
  funShow()
}

// 返回上一级页面
const goBack = () => {
  router.back()
}

// 新增库区信息弹窗
const dialogFormVisible = ref(false)
const OpenAdd = () => {
  form.id = 0
  form.warehouseCode = route.query.warehouseCode as string
  form.reservoirAreaCode = ''
  form.reservoirAreaName = ''
  form.area = ''
  form.descs = ''
  autoGenerate.value = false
  dialogFormVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  Object.assign(form, row)
  dialogFormVisible.value = true
}

// 保存
const handleSave = async () => {
  try {
    await formRef.value.validate()
    saveLoading.value = true
    const api = form.id ? '/api/WarehouseManagement/UpdateReservoirArea' : '/api/WarehouseManagement/CreateReservoirArea'
    await http.post(api, form)
    ElMessage.success(form.id ? '编辑成功' : '新增成功')
    dialogFormVisible.value = false
    funShow()
  } catch (error: any) {
    ElMessage.error((form.id ? '编辑' : '新增') + '失败：' + error.message)
  } finally {
    saveLoading.value = false
  }
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该库区?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      loading.value = true
      await http.post('/api/WarehouseManagement/DeleteReservoirArea', row)
      ElMessage.success('删除成功')
      funShow()
    } catch (error: any) {
      ElMessage.error('删除失败：' + error.message)
    } finally {
      loading.value = false
    }
  })
}

// 查看库位
const handleArea = (row: any) => {
  router.push({
    path: '/binlocation',
    query: {
      reservoirAreaCode: row.reservoirAreaCode,
      warehouseCode: route.query.warehouseCode
    }
  })
}

// 监听分页变化
watch(page, () => {
  funShow()
})

// 处理自动生成开关变化
const handleAutoGenerateChange = (val: boolean) => {
  if (val) {
    // 自动生成库区编号
    const timestamp = new Date().getTime()
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
    form.reservoirAreaCode = `RA${timestamp.toString().slice(-6)}${random}`
  } else {
    form.reservoirAreaCode = ''
  }
}

// 初始化
onMounted(() => {
  funShow()
})
</script>

<style lang="scss" scoped>
.reservoir-area-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 48px);
}

.page-header {
  margin-bottom: 24px;
  background-color: #fff;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
  }

  .header-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
  }
}

.search-card {
  margin-bottom: 24px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
  }

  .search-form {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .search-input {
    width: 300px;
  }
}

.table-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
  }

  .card-header {
    padding: 20px;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      display: flex;
      align-items: center;
      gap: 8px;

      .el-icon {
        font-size: 18px;
        color: #409eff;
      }
    }

    .add-button {
      padding: 8px 20px;
      font-weight: 500;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
      }
    }
  }

  .data-table {
    margin: 20px;
    
    :deep(.el-table__header) {
      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 600;
        height: 50px;
      }
    }

    :deep(.el-table__row) {
      td {
        padding: 12px 0;
        transition: background-color 0.3s;
      }

      &:hover {
        td {
          background-color: #f5f7fa;
        }
      }
    }

    :deep(.el-button--link) {
      padding: 4px 8px;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
      }
    }
  }
}

.pagination-container {
  padding: 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
}

.custom-dialog {
  :deep(.el-dialog__header) {
    margin: 0;
    padding: 20px;
    border-bottom: 1px solid #ebeef5;
    background-color: #f5f7fa;
    border-radius: 8px 8px 0 0;

    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }

  :deep(.el-dialog__body) {
    padding: 24px;
  }

  :deep(.el-dialog__footer) {
    padding: 16px 24px;
    border-top: 1px solid #ebeef5;
    background-color: #f5f7fa;
    border-radius: 0 0 8px 8px;
  }
}

.custom-form {
  .form-section {
    margin-bottom: 24px;
    
    &:last-child {
      margin-bottom: 0;
    }

    .section-title {
      font-size: 15px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 16px;
      display: flex;
      align-items: center;
      gap: 8px;

      .el-icon {
        font-size: 16px;
        color: #409eff;
      }
    }
  }

  .code-input-group {
    display: flex;
    align-items: center;
    gap: 16px;

    .code-input {
      flex: 1;
    }

    .auto-switch {
      min-width: 100px;
    }
  }

  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
  }

  :deep(.el-input__wrapper),
  :deep(.el-textarea__wrapper) {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 0 0 1px #409eff inset;
    }

    &.is-focus {
      box-shadow: 0 0 0 1px #409eff inset;
    }
  }

  :deep(.el-input-number__wrapper) {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 0 0 1px #409eff inset;
    }
  }

  :deep(.el-form-item) {
    margin-bottom: 18px;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.dialog-footer {
  text-align: right;

  .el-button {
    padding: 8px 20px;
    font-weight: 500;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-2px);
    }
  }
}

:deep(.el-button) {
  .el-icon {
    margin-right: 4px;
  }
}
</style>
